<script setup>
import { nextTick, ref, watch } from "vue";
import emitter from "../../utils/eventBus";
import { Local } from "../../utils/storage";
import { storeToRefs } from "pinia";
import { musicStore } from "@/store/music";
import { getLyric } from "../../apis/music";

import moment from "moment";
const { songId } = storeToRefs(musicStore());
const props = defineProps([
  "isPlaying",
  "currentTime",
  "maxTime",
  "musicDetail",
]);

const currentTime = ref();

// currentTime.value = props.currentTime;
let placeholderHeight = 0;
// 当前歌词索引
const lyricsIndex = ref(0);
//歌词
const lyric = ref([[0, "正在加载歌词"]]);

//关闭歌词页面
const offPlay = () => {
  emitter.emit("offPlay");
};
//监听歌曲变化和时间变化
watch(
  () => songId.value,
  (val) => {
    //重置歌词位置索引
    lyricsIndex.value = 0;
    songId.value = val;
    getLyrics(val);
  }
);
watch(
  () => props.currentTime,
  (currentTime1, lastTime) => {
    currentTime.value = lastTime;
    // 如果两个时间间隔有1秒,则可得知进度条被拖动 需要重新校准歌词index
    // 当歌词数量大于1并且索引为零时,可能歌词位置差距较大,走这个if进行快速跳转
    if (
      (lastTime && Math.abs(currentTime1 - lastTime) >= 1) ||
      (lyricsIndex.value == 0 && lyric.value.length > 1)
    ) {
      // 处理播放时间跳转时歌词位置的校准
      if (lyric.value.length > 1) {
        getCurrentLyricsIndex(currentTime1);
        // 滑动到当前歌词
        lyricScroll(lyricsIndex.value);
      }
    }
    // 根据实时播放时间实现歌词滚动
    if (lyricsIndex.value < lyric.value.length) {
      if (currentTime1 >= lyric.value[lyricsIndex.value][0]) {
        lyricsIndex.value += 1;
        lyricScroll(lyricsIndex.value);
      }
    }
  }
);

watch(
  () => lyric.value,
  (current) => {
    // 大于一秒，说明歌词在1秒后才请求成功 歌词可能不能马上跳转到当前时间 这里进行校准
    if (props.currentTime > 1) {
      // 处理播放时间跳转时歌词位置的校准
      if (lyric.value.length > 1) {
        getCurrentLyricsIndex(props.currentTime);
        nextTick(() => {
          // 滑动到当前歌词
          lyricScroll(lyricsIndex.value);
        });
      }
    }
  }
);

const musicChange = (type) => {
  if (type == 1) {
    emitter.emit("beforeMusic");
  } else {
    emitter.emit("nextMusic");
  }
};

const handlePlay = (type) => {
  if (type == "play") {
    emitter.emit("playSong");
  } else {
    emitter.emit("pauseSong");
  }
};

const handleSlider = (data) => {
  emitter.emit("sliderStep", data);
};

//获取歌词
const getLyrics = async (id) => {
  let res = await getLyric({ id: id });
  if (!res.lrc) {
    lyric.value = [[0, "暂无歌词"]];
    return;
  }
  let lyrics = res.lrc.lyric;
  // 对获取到的歌词进行处理
  let arr = lyrics.split("\n");
  let array = [];
  // let obj = {};
  let time = "";
  let value = "";
  let result = [];

  //去除空行
  arr.forEach((item) => {
    if (item != "") {
      array.push(item);
    }
  });
  arr = array;
  arr.forEach((item) => {
    time = item.split("]")[0];
    value = item.split("]")[1];
    //去掉时间里的中括号得到xx:xx.xx
    var t = time.slice(1).split(":");
    //将结果压入最终数组
    result.push([parseInt(t[0], 10) * 60 + parseFloat(t[1]), value]);
  });

  lyric.value = result;
};
if (songId.value) {
  getLyrics(songId.value);
}

// 实现歌词滚动
const lyricScroll = (currentLyric) => {
  // 获取歌词item
  let lyricsArr = document.querySelectorAll(".lyricsItem");
  // 获取歌词框
  let lyrics = document.querySelector(".lyrics");
  // placeholder的高度
  if (placeholderHeight == 0) {
    placeholderHeight = lyricsArr[0].offsetTop - lyrics.offsetTop;
  }
  //   歌词item在歌词框的高度 = 歌词框的offsetTop - 歌词item的offsetTop
  if (lyricsArr[currentLyric - 1]) {
    let distance = lyricsArr[currentLyric - 1].offsetTop - lyrics.offsetTop;
    //   lyricsArr[currentLyric].scrollIntoView();
    lyrics.scrollTo({
      behavior: "smooth",
      top: distance - placeholderHeight,
    });
  }
};

//获取当前歌词索引
const getCurrentLyricsIndex = (currentTime) => {
  let lyricsIndexs = 0;
  lyric.value.some((item) => {
    if (lyricsIndexs < lyric.value.length - 1) {
      if (currentTime > item[0]) {
        lyricsIndexs += 1;
      }
      return currentTime <= item[0];
    }
  });
  lyricsIndex.value = lyricsIndexs;
};
</script>

<template>
  <header-bar></header-bar>
  <div class="container-play wrapper">
    <div @click="offPlay" class="offPlay">
      <i class="iconfont icon-arrow-down"></i>
    </div>
    <div class="content-wrap">
      <div class="left">
        <div class="music_info">
          <div v-if="musicDetail" class="detail_content">
            <div class="cover">
              <el-image
                :preview-src-list="[musicDetail.al.picUrl]"
                :src="musicDetail.al.picUrl + `${'?param=500y500'}`"
                fit="cover"
              ></el-image>
            </div>
            <div v-if="musicDetail.name" class="music_info">
              <div class="info_wrap">
                <div class="music_name">{{ musicDetail.name }}</div>
                <div class="singer_name">{{ musicDetail.ar[0].name }}</div>
              </div>
              <div class="like_btn">
                <i class="iconfont icon-aixin"></i>
              </div>
            </div>
            <div class="progress_wrap">
              <span>{{ moment(currentTime * 1000).format("mm:ss") }}</span>
              <div class="slide_time">
                <el-slider
                  @change="handleSlider"
                  :show-tooltip="false"
                  :max="maxTime"
                  v-model="currentTime"
                ></el-slider>
              </div>
              <span>{{ moment(maxTime * 1000).format("mm:ss") }}</span>
            </div>
            <div class="play_wrap">
              <div class="play_btn">
                <!-- //上一首 -->
                <i
                  @click="musicChange(1)"
                  class="iconfont icon-shangyishou"
                ></i>
                <!-- 播放歌曲 -->
                <i
                  @click="handlePlay('play')"
                  v-if="!isPlaying"
                  class="iconfont icon-bofang"
                ></i>
                <!-- 暂停播放 -->
                <i
                  @click="handlePlay('pause')"
                  v-else
                  class="iconfont icon-pause-full"
                ></i>
                <!-- 下一首 -->
                <i @click="musicChange(2)" class="iconfont icon-xiayishou"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="right">
        <div class="lyrics">
          <!-- 占位 -->
          <div class="placeholder"></div>
          <!-- 因为歌词快了一句,所以减1 -->
          <!-- 歌词item -->
          <div
            class="lyricsItem"
            :class="lyricsIndex - 1 == index ? 'currentLyric' : ''"
            v-for="(item, index) in lyric"
            :key="index"
          >
            {{ item[1] }}
          </div>
          <!-- 占位 -->
          <div class="placeholder"></div>
          <!-- <div>{{currentTime}}</div> -->
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.container-play {
  height: 100vh;

  .offPlay {
    -webkit-app-region: no-drag;
    margin-left: 20px;
    margin-top: -10px;
    z-index: 10;
    width: 40px;
    height: 40px;
    font-size: 20px;
    font-weight: 600;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: all 0.3s;
    border-radius: 5px;
    cursor: pointer;
    &:hover {
      background-color: #eee;
      color: rgb(80, 65, 219);
    }
  }
  .content-wrap {
    height: 100%;
    display: flex;
    .left {
      flex: 3;
      .music_info {
        margin-top: 50px;
        .detail_content {
          // height: 100%;
          padding: 0;
          z-index: 5;
          display: flex;
          flex-direction: column;
          align-items: center;
          .cover {
            display: flex;
            width: 530px;
            height: 530px;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            .el-image {
              border-radius: 20px;
              width: 100%;
              height: 100%;
              box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12),
                0 0 6px rgba(0, 0, 0, 0.04);
            }
          }

          .music_info {
            margin-top: 50px;
            width: 530px;
            display: flex;
            justify-content: space-between;
            .info_wrap {
              // margin-left: 10px;
              .music_name {
                font-size: 20px;
                font-weight: 600;
                color: #fff;
              }
              .singer_name {
                margin-top: 10px;
                font-size: 15px;
                font-weight: 600;
                color: rgb(224, 214, 214);
              }
            }
            .like_btn {
              i {
                opacity: 0.8;
                font-size: 20px;
                font-weight: 600;
                color: #fff;
              }
            }
          }

          .progress_wrap {
            width: 530px;
            height: 25px;
            display: flex;
            line-height: 25px;
            padding-bottom: 5px;
            margin-top: 20px;
            span {
              font-size: 15px;
              color: #fff;
            }
            .slide_time {
              width: 100%;
              display: flex;
              justify-content: center;
              align-items: center;
              :deep(.el-slider) {
                width: 90%;
                .el-slider__bar {
                  height: 4px;
                  background-color: rgb(209, 198, 207);
                }
                .el-slider__runway {
                  margin: 0;
                  background-color: #e0eaf3;
                  height: 4px;
                  border-radius: 0;
                }
                .el-tooltip {
                  height: 0px;
                  width: 0px;
                  border: none;
                }
                .el-slider__button-wrapper {
                  width: 1px;
                  height: 1px;
                  .el-slider__button {
                    border: 1px solid #eee;
                    background-color: #eee;
                    margin-top: 13px;
                    width: 8px;
                    height: 8px;
                  }
                }
              }
            }
          }
          .play_wrap {
            width: 400px;
            display: flex;
            justify-content: center;
            .play_btn {
              width: 35%;
              display: flex;
              justify-content: space-between;
              i {
                color: #fff;
                font-size: 25px;
                font-weight: 600;
                padding: 5px;
                border-radius: 5px;
                transition: all 0.3s;
                &:hover {
                  background-color: rgb(121, 119, 223);
                }
              }
            }
          }
        }
      }
    }
    .right {
      height: calc(100% - 100px);
      flex: 2;
      .lyrics {
        width: 100%;
        height: 100%;
        font-size: 23px;
        text-align: left;
        overflow-y: scroll;
        scrollbar-width: none;
        /* overflow: scroll; */
      }

      .lyrics::-webkit-scrollbar {
        display: none;
      }
      .lyricsItem {
        font-size: 25px;
        font-weight: 600;
        margin: 15px;
        color: #838d7a;
        transition: all 0.5s;
        padding: 8px 0;
      }
      .currentLyric {
        font-weight: 600;
        /* font-size: 15px; */
        color: #fff;
      }

      .placeholder {
        width: 100%;
        height: 30%;
      }
    }
  }
}
</style>
